/*
 * @Author: duapple
 * @Date: 2021-11-16 14:42:31
 * @LastEditTime: 2021-11-19 10:56:06
 * @LastEditors: duapple
 * @Description: Add description
 * @FilePath: /gateway/file/file.go
 * Copyright (c) 2011 duapple - All rights reserved.
 */
package file

import (
	"encoding/json"
	"errors"
	"os"

	log "github.com/sirupsen/logrus"
)

type GetConfiger interface {
}

var config_file string = ""

type GlobalConfig map[string]interface{}

/* 全局配置 */
var gblConf = &GlobalConfig{}

/**
 * @description: 保存数据到配置文件，不同配置，key不能一样，否则配置会被覆盖
 * @param {GetConfiger} conf 需要保存的数据
 * @param {string} key 数据对应的json key
 * @return {*}
 */
func Write(conf GetConfiger, key string) {
	gblConf.set(key, conf)
	data, err := json.MarshalIndent(gblConf, "", "\t")
	if err != nil {
		log.Error(err)
		return
	}
	err = os.WriteFile(config_file, data, 0666)
	if err != nil {
		log.Error(err)
	}
}

/**
 * @description: 从全局配置中读取某个数据的内容，使用前需要使用 ReadFile() 先从文件中读取配置
 * @param {GetConfiger} g 用于保存读取数据的
 * @param {string} key 配置对应的json key
 * @return {*}
 */
func Read(g GetConfiger, key string) error {
	return gblConf.getConfigToStruct(g, key)
}

/**
 * @description: 从文件读取全局配置
 * @param {*}
 * @return {*}
 */
func ReadFile(file string) {
	config_file = file
	if config_file == "" {
		config_file = "global.json"
	}
	log.Info("Loading configuration file: ", config_file)
	data, err := os.ReadFile(config_file)
	if err != nil {
		log.Warn(err)
		return
	}
	err = json.Unmarshal(data, gblConf)
	if err != nil {
		log.Warn(err)
		return
	}
}

func (gb *GlobalConfig) getConfigToStruct(gi GetConfiger, key string) error {
	gs := map[string]interface{}(*gb)[key]
	if gs == nil {
		err := errors.New("interface{} is nil for parse")
		log.Warn(err)
		return err
	}
	data, err := json.Marshal(gs)
	if err != nil {
		log.Error(err)
		return err
	}
	err = json.Unmarshal(data, gi)
	if err != nil {
		log.Error(err)
	}
	return err
}

func (gb *GlobalConfig) set(key string, gi GetConfiger) {
	map[string]interface{}(*gb)[key] = gi
}
